package com.myapp.ruyixing.ui.shopmanager;

import static android.view.View.GONE;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.myapp.ruyixing.R;
import com.myapp.ruyixing.ui.BaseActivity;
import com.myapp.ruyixing.ui.CityListActivity;
import com.myapp.ruyixing.ui.MainActivity;
import com.myapp.ruyixing.utils.LoginHelper;
import com.myapp.ruyixing.utils.LoginHelper.ILoginListener;

public class LoginActivity extends BaseActivity implements OnClickListener,
		ILoginListener {

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);

		setContentView(R.layout.activity_shopmanager_login);

		String username = LoginHelper.getInstance().getShopUserName();
		if (!TextUtils.isEmpty(username)) {
			((EditText) (findViewById(R.id.edit_account))).setText(username);
			findViewById(R.id.edit_password).requestFocus();
		}
		findViewById(R.id.btn_commit).setOnClickListener(this);
	}

	private void showToast(String msg) {
		Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
	}

	public void showLoading(boolean show, String msg) {
		if (isFinishing()) {
			return;
		}
		if (show) {
			findViewById(R.id.layout_loading).setVisibility(View.VISIBLE);
			((TextView) findViewById(R.id.text_loading)).setText(msg);
		} else {
			findViewById(R.id.layout_loading).setVisibility(GONE);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_commit:
			String username = ((EditText) findViewById(R.id.edit_account))
					.getText().toString().trim();
			if (TextUtils.isEmpty(username)) {
				findViewById(R.id.edit_account).requestFocus();
				showToast("账号不能为空！");
				return;
			}
			String password = ((EditText) findViewById(R.id.edit_password))
					.getText().toString().trim();
			if (TextUtils.isEmpty(password)) {
				findViewById(R.id.edit_password).requestFocus();
				showToast("密码不能为空！");
				return;
			}
			LoginHelper.getInstance().doShopLogin(username, password, this);
			showLoading(true, "登录中...");
			break;
		default:
			break;
		}
	}

	@Override
	public void onLoginSuccess() {
		showLoading(false, null);
		CityListActivity.setCity(this, LoginHelper.getInstance()
				.getShopCityName(), LoginHelper.getInstance().getShopCityId());
		Intent i = new Intent(LoginActivity.this, MainActivity.class);
		startActivity(i);
		finish();
	}

	@Override
	public void onLoginFail(int errorNo) {
		showLoading(false, null);
		showToast("登陆失败，请检查网络和用户名密码");
	}
}
